// 增强版数据库配置 - 安全强化和连接可靠性
import dotenv from 'dotenv';
import path from 'path';
import { fileURLToPath } from 'url';
import crypto from 'crypto';

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const projectRoot = path.resolve(__dirname, '..');

dotenv.config({ path: path.join(projectRoot, '.env') });

class DatabaseSecurity {
    // 密码强度验证
    static validatePasswordStrength(password) {
        if (!password || password.length < 12) {
            throw new Error('密码长度必须至少12个字符');
        }
        
        const hasUpperCase = /[A-Z]/.test(password);
        const hasLowerCase = /[a-z]/.test(password);
        const hasNumbers = /\d/.test(password);
        const hasSpecialChars = /[!@#$%^&*(),.?":{}|<>]/.test(password);
        
        if (!hasUpperCase || !hasLowerCase || !hasNumbers || !hasSpecialChars) {
            throw new Error('密码必须包含大小写字母、数字和特殊字符');
        }
        
        return true;
    }
    
    // 生成强密码
    static generateStrongPassword(length = 16) {
        const charset = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*()';
        let password = '';
        for (let i = 0; i < length; i++) {
            password += charset.charAt(Math.floor(Math.random() * charset.length));
        }
        return password;
    }
    
    // 加密敏感数据
    static encryptData(data, key) {
        const algorithm = 'aes-256-gcm';
        const iv = crypto.randomBytes(16);
        const cipher = crypto.createCipher(algorithm, key);
        
        let encrypted = cipher.update(data, 'utf8', 'hex');
        encrypted += cipher.final('hex');
        
        const authTag = cipher.getAuthTag();
        
        return {
            iv: iv.toString('hex'),
            encryptedData: encrypted,
            authTag: authTag.toString('hex')
        };
    }
    
    // 解密数据
    static decryptData(encryptedData, key) {
        const algorithm = 'aes-256-gcm';
        const decipher = crypto.createDecipher(algorithm, key);
        
        decipher.setAuthTag(Buffer.from(encryptedData.authTag, 'hex'));
        decipher.setAAD(Buffer.from(encryptedData.iv, 'hex'));
        
        let decrypted = decipher.update(encryptedData.encryptedData, 'hex', 'utf8');
        decrypted += decipher.final('utf8');
        
        return decrypted;
    }
}

class ConnectionManager {
    constructor() {
        this.connections = new Map();
        this.retryAttempts = 0;
        this.maxRetries = 5;
        this.retryDelay = 2000;
    }
    
    // 连接重试机制
    async withRetry(operation, operationName) {
        for (let attempt = 1; attempt <= this.maxRetries; attempt++) {
            try {
                return await operation();
            } catch (error) {
                if (attempt < this.maxRetries) {
                    console.warn(`⚠️ ${operationName} 失败 (尝试 ${attempt}/${this.maxRetries}):`, error.message);
                    await new Promise(resolve => setTimeout(resolve, this.retryDelay * attempt));
                } else {
                    throw new Error(`${operationName} 最终失败: ${error.message}`);
                }
            }
        }
    }
    
    // 健康检查
    async healthCheck() {
        const results = {};
        
        for (const [name, connection] of this.connections) {
            try {
                if (connection.healthCheck) {
                    results[name] = await connection.healthCheck();
                } else {
                    results[name] = { status: 'unknown', message: '无健康检查方法' };
                }
            } catch (error) {
                results[name] = { status: 'unhealthy', message: error.message };
            }
        }
        
        return results;
    }
}

// 增强版数据库配置
const enhancedConfig = {
    // 应用配置
    app: {
        name: process.env.APP_NAME || 'bike-wholesale-app',
        version: process.env.APP_VERSION || '2.0.0',
        environment: process.env.NODE_ENV || 'development',
        logLevel: process.env.LOG_LEVEL || 'info'
    },

    // 数据库配置 - 安全强化版
    database: {
        // PostgreSQL - 主数据库
        postgresql: {
            host: process.env.DB_HOST || 'localhost',
            port: parseInt(process.env.DB_PORT) || 5432,
            name: process.env.DB_NAME || 'bike_wholesale',
            user: process.env.DB_USER || 'postgres',
            password: process.env.DB_PASSWORD || DatabaseSecurity.generateStrongPassword(),
            
            // 连接池优化
            maxConnections: parseInt(process.env.DB_MAX_CONNECTIONS) || 25,
            idleTimeout: parseInt(process.env.DB_IDLE_TIMEOUT) || 30000,
            connectionTimeout: parseInt(process.env.DB_CONNECTION_TIMEOUT) || 5000,
            
            // SSL配置
            ssl: process.env.DB_SSL === 'true' ? {
                rejectUnauthorized: false,
                ca: process.env.DB_SSL_CA,
                cert: process.env.DB_SSL_CERT,
                key: process.env.DB_SSL_KEY
            } : false,
            
            // 重试配置
            retry: {
                max: parseInt(process.env.DB_RETRY_MAX) || 3,
                delay: parseInt(process.env.DB_RETRY_DELAY) || 1000
            },
            
            // 监控配置
            statement_timeout: parseInt(process.env.DB_STATEMENT_TIMEOUT) || 30000,
            idle_in_transaction_session_timeout: parseInt(process.env.DB_IDLE_TX_TIMEOUT) || 60000
        },

        // Redis - 缓存数据库
        redis: {
            host: process.env.REDIS_HOST || 'localhost',
            port: parseInt(process.env.REDIS_PORT) || 6379,
            password: process.env.REDIS_PASSWORD || DatabaseSecurity.generateStrongPassword(20),
            db: parseInt(process.env.REDIS_DB) || 0,
            keyPrefix: process.env.REDIS_KEY_PREFIX || 'bike_secure:',
            
            // 连接优化
            socket: {
                keepAlive: 30000,
                reconnectStrategy: (retries) => Math.min(retries * 100, 3000)
            },
            
            // 安全配置
            tls: process.env.REDIS_TLS === 'true' ? {} : undefined,
            
            // 重试配置
            retry: {
                max: parseInt(process.env.REDIS_RETRY_MAX) || 5,
                delay: parseInt(process.env.REDIS_RETRY_DELAY) || 500
            }
        },

        // MongoDB - 文档数据库
        mongodb: {
            uri: process.env.MONGODB_URI || 'mongodb://localhost:27017/bike_community',
            db: process.env.MONGODB_DB || 'bike_community',
            
            // 连接池优化
            poolSize: parseInt(process.env.MONGODB_POOL_SIZE) || 15,
            bufferMaxEntries: parseInt(process.env.MONGODB_BUFFER_MAX_ENTRIES) || -1,
            
            // SSL配置
            ssl: process.env.MONGODB_SSL === 'true',
            sslValidate: process.env.MONGODB_SSL_VALIDATE === 'true',
            sslCA: process.env.MONGODB_SSL_CA,
            sslCert: process.env.MONGODB_SSL_CERT,
            sslKey: process.env.MONGODB_SSL_KEY,
            
            // 认证配置
            authSource: process.env.MONGODB_AUTH_SOURCE || 'admin',
            
            // 重试配置
            retryWrites: process.env.MONGODB_RETRY_WRITES !== 'false',
            retryReads: process.env.MONGODB_RETRY_READS !== 'false',
            
            // 超时配置
            connectTimeoutMS: parseInt(process.env.MONGODB_CONNECT_TIMEOUT) || 10000,
            socketTimeoutMS: parseInt(process.env.MONGODB_SOCKET_TIMEOUT) || 45000,
            serverSelectionTimeoutMS: parseInt(process.env.MONGODB_SERVER_SELECTION_TIMEOUT) || 30000
        },

        // SQLite - 备用数据库
        sqlite: {
            file: process.env.SQLITE_FILE || 'data/bike_wholesale.db',
            timeout: parseInt(process.env.SQLITE_TIMEOUT) || 5000,
            
            // 性能优化
            journalMode: process.env.SQLITE_JOURNAL_MODE || 'WAL',
            synchronous: process.env.SQLITE_SYNCHRONOUS || 'NORMAL',
            cacheSize: parseInt(process.env.SQLITE_CACHE_SIZE) || -2000,
            
            // 安全配置
            foreignKeys: process.env.SQLITE_FOREIGN_KEYS !== 'false',
            busyTimeout: parseInt(process.env.SQLITE_BUSY_TIMEOUT) || 3000
        }
    },

    // 安全配置 - 强化版
    security: {
        // JWT配置
        jwt: {
            secret: process.env.JWT_SECRET || DatabaseSecurity.generateStrongPassword(32),
            expiresIn: process.env.JWT_EXPIRES_IN || '7d',
            issuer: process.env.JWT_ISSUER || 'bike-wholesale-app',
            audience: process.env.JWT_AUDIENCE || 'bike-wholesale-users',
            
            // 刷新令牌配置
            refreshToken: {
                secret: process.env.JWT_REFRESH_SECRET || DatabaseSecurity.generateStrongPassword(32),
                expiresIn: process.env.JWT_REFRESH_EXPIRES_IN || '30d'
            }
        },

        // 密码策略
        passwordPolicy: {
            minLength: parseInt(process.env.PASSWORD_MIN_LENGTH) || 12,
            requireUppercase: process.env.PASSWORD_REQUIRE_UPPERCASE !== 'false',
            requireLowercase: process.env.PASSWORD_REQUIRE_LOWERCASE !== 'false',
            requireNumbers: process.env.PASSWORD_REQUIRE_NUMBERS !== 'false',
            requireSpecialChars: process.env.PASSWORD_REQUIRE_SPECIAL_CHARS !== 'false',
            maxAgeDays: parseInt(process.env.PASSWORD_MAX_AGE_DAYS) || 90,
            historySize: parseInt(process.env.PASSWORD_HISTORY_SIZE) || 5
        },

        // 会话安全
        session: {
            cookieName: process.env.SESSION_COOKIE_NAME || 'bike_session',
            secure: process.env.NODE_ENV === 'production',
            httpOnly: true,
            sameSite: 'strict',
            maxAge: 24 * 60 * 60 * 1000 // 24小时
        },

        // 加密配置
        encryption: {
            algorithm: 'aes-256-gcm',
            keyRotationDays: parseInt(process.env.ENCRYPTION_KEY_ROTATION_DAYS) || 30
        }
    },

    // 连接监控配置
    monitoring: {
        enabled: process.env.MONITORING_ENABLED !== 'false',
        metricsPort: parseInt(process.env.METRICS_PORT) || 9090,
        healthCheckInterval: parseInt(process.env.HEALTH_CHECK_INTERVAL) || 30000,
        
        // 数据库监控
        database: {
            slowQueryThreshold: parseInt(process.env.SLOW_QUERY_THRESHOLD) || 1000,
            connectionPoolMonitoring: process.env.CONNECTION_POOL_MONITORING !== 'false'
        }
    }
};

// 验证生产环境配置
if (enhancedConfig.app.environment === 'production') {
    const requiredEnvVars = [
        'JWT_SECRET', 'DB_HOST', 'DB_NAME', 'DB_USER', 'DB_PASSWORD',
        'REDIS_PASSWORD'
    ];
    
    const missingVars = requiredEnvVars.filter(varName => !process.env[varName]);
    
    if (missingVars.length > 0) {
        console.error('❌ 生产环境缺少必需的环境变量:', missingVars.join(', '));
        console.error('💡 请在 .env 文件中设置这些变量');
        process.exit(1);
    }
    
    // 验证密码强度
    try {
        DatabaseSecurity.validatePasswordStrength(process.env.DB_PASSWORD);
        DatabaseSecurity.validatePasswordStrength(process.env.REDIS_PASSWORD);
        console.log('✅ 数据库密码强度验证通过');
    } catch (error) {
        console.error('❌ 数据库密码强度不足:', error.message);
        console.log('💡 建议使用强密码或启用自动生成');
    }
}

// 导出配置和工具类
export default enhancedConfig;
export { DatabaseSecurity, ConnectionManager };